<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
  <title>默认点标记</title>
  <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
  <style>
    html,
    body,
    #container {
      height: 100%;
      width: 100%;
    }

    .amap-icon img,
    .amap-marker-content img {
      width: 25px;
      height: 34px;
    }

    .marker {
      position: absolute;
      top: -20px;
      right: -118px;
      color: #fff;
      padding: 4px 10px;
      box-shadow: 1px 1px 1px rgba(10, 10, 10, .2);
      white-space: nowrap;
      font-size: 12px;
      font-family: "";
      background-color: #25A5F7;
      border-radius: 3px;
    }

    .input-card {
      width: 18rem;
      z-index: 170;
    }

    .input-card .btn {
      margin-right: .8rem;
    }

    .input-card .btn:last-child {
      margin-right: 0;
    }

    /* 自定义点坐标内容样式 */
    .custom-content-marker {
      position: relative;
      width: 25px;
      height: 34px;
    }

    .custom-content-marker img {
      width: 100%;
      height: 100%;
    }

    .custom-content-marker .close-btn {
      position: absolute;
      top: -6px;
      right: -8px;
      width: 15px;
      height: 15px;
      font-size: 12px;
      background: #ccc;
      border-radius: 50%;
      color: #fff;
      text-align: center;
      line-height: 15px;
      box-shadow: -1px 1px 1px rgba(10, 10, 10, .2);
    }

    .custom-content-marker .close-btn:hover {
      background: #666;
    }
  </style>
</head>

<body>
  <div id="container"></div>
  <div class="input-card">
    <label style="color:grey">点标记操作</label>
    <div class="input-item">
      <input type="button" class="btn" onclick="addMarker()" value="添加点标记">
      <!-- <input type="button" class="btn" onclick="updateIcon()" value="更新点标记图标"> -->
    </div>
    <div class="input-item">
      <input type="button" class="btn" onclick="clearMarker()" value="删除点标记">
      <input type="button" class="btn" onclick="updateContent()" value="更新点标记内容">
    </div>
  </div>
  <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=5fbb835dccc98df761a27aa9fadbf1f7"></script>
  <script type="text/javascript">
    var markers = []; // 用于存储所有点标记的数组
    var map = new AMap.Map("container", {
      resizeEnable: true,
      center: [116.397428, 39.90923],
      zoom: 13
    });

    var markerCount = 0;


    function render() {
      //刚进入页面就开始通过js渲染数据
      var request = new XMLHttpRequest();
      request.open('GET', 'your_backend_url', true); // 替换为你的后端 URL
      request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
          var responseData = JSON.parse(request.responseText);
          markerCount = responseData.markerCount;
        }
      };
      request.send();
    }

    window.addEventListener('load', function () {
      render() //事件在整个页面及所有依赖资源如样式表和图片都已完成加载时触发
    })


    // 实例化点标记
    function addMarker() {
      //点标记显示内容
      const markerContent = `<div class="custom-content-marker">
      <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">
      <div class="close-btn" onclick="clearSingleMarker(${markerCount})">X</div>
      </div>`


      // 发送AJAX请求获取标记点数
      // var request = new XMLHttpRequest();
      // request.open('GET', 'your_backend_url', true); //发送数据到后端请求用户的标记点数
      // request.onreadystatechange = function () {
      //   if (request.readyState === 4 && request.status === 200) {
      //     var responseData = JSON.parse(request.responseText);
      //     markerCount = responseData.markerCount;
      //   }
      // };
      // request.send();

      var marker = new AMap.Marker({
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        offset: new AMap.Pixel(-13, -30),
        position: [116.406315, 39.908775],
        // 设置是否可以拖拽
        draggable: true,
        cursor: 'move',
        // 设置拖拽效果
        raiseOnDrag: true,
        content: markerContent, //将 html 传给 content
        extData: {
          id: `${markerCount++}`  //自定义属性 从数据库中查询对应用户的标记点数
        }
      });
      marker.setMap(map);

      console.log(marker.getExtData())

      // 获取当前点标记的经纬度
      var position = marker.getPosition();

      // 向后端发送请求将经纬度添加到数据库
      var request = new XMLHttpRequest();
      request.open('POST', 'your_backend_url', true);
      request.setRequestHeader('Content-Type', 'application/json');
      request.onreadystatechange = function () {
        if (request.readyState === 4 && request.status === 200) {
          console.log('点标记已添加到数据库');
        }
      };
      var data = {
        latitude: position.lat,
        longitude: position.lng
      };
      request.send(JSON.stringify(data));//将 JavaScript 对象 data 转换为 JSON 字符串，并将其作为请求的主体发送到服务器。

      markers.push(marker); // 将点标记添加到数组中
    }

    // 后续自定义
    // function updateIcon() {
    //   var marker = markers[markers.length - 1]; // 获取最后一个点标记
    //   // console.log(markers)
    //   marker.setIcon('//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png')
    // }

    function updateContent() {
      var marker = markers[markers.length - 1]; // 获取最后一个点标记

      // 自定义点标记内容
      var markerContent = document.createElement("div");

      // 点标记中的图标
      var markerImg = document.createElement("img");
      markerImg.className = "markerlnglat";
      markerImg.src = "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png";
      markerImg.setAttribute('width', '25px');
      markerImg.setAttribute('height', '34px');
      markerContent.appendChild(markerImg);

      // 点标记中的文本
      var markerSpan = document.createElement("span");
      markerSpan.className = 'marker';
      markerSpan.innerHTML = "Hi，我被更新啦！";
      markerContent.appendChild(markerSpan);

      marker.setContent(markerContent); // 更新点标记内容
      marker.setPosition([116.391467, 39.927761]); // 更新点标记位置
    }

    // 清除所有 marker
    function clearMarker() {
      for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
      }
      markers = [];
    }

    //清除单个marker
    function clearSingleMarker(index) {
      console.log(index)
      markers[index].setMap(null)
      markers.splice(index, 1, "null")
      console.log(markers)
    }


  </script>
</body>

</html>